
type CallbackType = (message: any) => void;

type Subscribers = {
    equipmentMsg: CallbackType[];
    trayMsg: CallbackType[];
    scanEquipmentMsg: CallbackType[];
    communicationMsg: CallbackType[];
};


class WebSocketService {
    url: string;
    websocket: WebSocket | null;
    subscribers: Subscribers;
    reconnectAttempts: number = 0; // 重连尝试次数

    constructor(url: string) {
        this.url = url;
        this.websocket = null;

        this.subscribers = {
            equipmentMsg: [],
            trayMsg: [],
            scanEquipmentMsg: [],
            communicationMsg: [],
        };
    }

    connect(): void {
        if (this.reconnectAttempts > 5) { // 最多重连5次
            console.log("Max reconnect attempts reached");
            return;
        }
        this.websocket = new WebSocket(this.url);

        this.websocket.onopen = () => {
            console.log("WebSocket connected");
            this.reconnectAttempts = 0; // 连接成功时重置尝试次数
        };

        this.websocket.onmessage = (event: MessageEvent) => {
            const data = JSON.parse(event.data);
            if (typeof data !== 'object' || !data) {
                console.warn("Unexpected message structure");
                return;
            }

            for (const [key, value] of Object.entries(data)) {
                if (this.subscribers[key as keyof Subscribers]) {
                    this.subscribers[key as keyof Subscribers].forEach(callback => callback(value));
                }
            }
        };


        this.websocket.onerror = (event: Event) => {
            console.error("WebSocket error:", event);
        };

        this.websocket.onclose = () => {
            console.log("WebSocket closed, reconnecting...");
            setTimeout(() => this.connect(), 1000 * (this.reconnectAttempts + 1)); // 逐渐增加重连延迟
            this.reconnectAttempts++;
        }
    }

    subscribe(key: keyof Subscribers, callback: CallbackType): void {
        if (this.subscribers[key]) {
            this.subscribers[key].push(callback);
        } else {
            console.warn(`Unknown key: ${key}`);
        }
    }

    unsubscribe(key: keyof Subscribers, callback: CallbackType): void {
        if (this.subscribers[key]) {
            const index = this.subscribers[key].indexOf(callback);
            if (index > -1) {
                this.subscribers[key].splice(index, 1);
            }
        }
    }

    send(data: any): void {
        if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
            this.websocket.send(JSON.stringify(data));
        } else {
            console.warn("WebSocket not connected");
        }
    }
}

// 创建一个WebSocketService的单例
const webSocketService = new WebSocketService("ws://100.100.100.200:18081/websockets/aibangplc");

// 连接到WebSocket服务器
webSocketService.connect();

export default webSocketService;

